import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# =====================================================
#             ○  元素识别等 ○               #
# =====================================================
# 测试用例中所需的动作控制
class WebControl():
    def __init__(self):
        super().__init__()

    # 找到xpath元素并截图至pics目录
    def screenshot_ocr(self,driver,xpath, PicName):
        target_element = WebDriverWait(driver, 30).until(
            EC.presence_of_element_located((By.XPATH, xpath)))
        target_element.screenshot("pics\\" + PicName + ".png")

    # 点击操作
    def Click(self,driver, xpath):
        exec_span = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, xpath)))
        driver.execute_script("arguments[0].click();", exec_span)

    # 输入文本框操作
    def sendkeys(self,driver,xpath,msg):
        path_element = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, xpath)))
        path_element.click()
        path_element.clear()
        path_element.send_keys(msg)

    # 切换至其它定位的iframe框架并判断是否切换成功
    def switch_frame(self,driver,xpath,assertxpath,expected_text):
        # 进入到xpath对应的iframe
        WebDriverWait(driver, 30).until(
            EC.frame_to_be_available_and_switch_to_it((By.XPATH, xpath)))

        # 在 iframe 中断言某个元素是否存在
        target_element = WebDriverWait(driver, 30).until(
            EC.presence_of_element_located((By.XPATH, assertxpath)))

        if target_element.text == expected_text:
            return "success"
        else:
            return "fail"
